#pragma once

#include <iostream>
#include <functional>
#include "InetAddr.hpp"
#include "Log.hpp"
// #include "Reactor.hpp"

class Connection;
class Reactor;
using func_t = std::function<void (Connection*)>;

// 从文件描述符中读写数据，处理异常
class Connection
{
public:
    Connection(int sockfd)
        :_sockfd(sockfd)
    {}

    void SetEvents(int events)
    {
        _events = events;
    }

    void Register(func_t recver, func_t sender, func_t excepter)
    {
        _recver = recver;
        _sender = sender;
        _excepter = excepter;
    }

    void SetSelf(Reactor* self)
    {
        _R = self;
    }

    int GetSockfd()
    {
        return _sockfd;
    }

    uint32_t GetEvents()
    {
        return _events;
    }

    void AppendInbuffer(const std::string& buffer)
    {
        _inbuffer += buffer;
    }

    void AppendOutBuffer(const std::string& buffer)
    {
        _outbuffer += buffer;
    }

    void OutbufferRemove(int n)
    {
        _outbuffer.erase(0, n);
    }

    bool OutbufferEmpty()
    {
        return _outbuffer.empty();
    }

    std::string& GetInbuffer()
    {
        return _inbuffer;
    }

    std::string& GetOutbuffer()
    {
        return _outbuffer;
    }

    void Close()
    {
        if(_sockfd >= 0)
            ::close(_sockfd);
    }

    ~Connection()
    {}
private:
    int _sockfd;
    std::string _inbuffer; // 读缓冲区
    std::string _outbuffer; // 写缓冲区
    // inetaddr::InetAddr _addr; // ....
    uint32_t _events; // Connection 对象中关心的事件集合
public:
    func_t _recver;
    func_t _sender;
    func_t _excepter;
    Reactor* _R;
};